package com.google.appengine.codelab;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query.Filter;

public class BaseKind {
	
	protected int checkDelete(Entity entity, Iterable<Entity> entities) {
		if ((entity != null) && ((entities == null) || (!hasEntity(entities)))) {
			Util.deleteEntity(entity.getKey());
			return 0;
		}
		return -1;
	}
	
	protected int delete(String kind, String propertyName, long key) {
		Entity entity = Datastore.get(getKindName(), key);
		Iterable<Entity> entities = null;
		if (kind != "") {
			entities = Datastore.get(kind, propertyName, key).asIterable();
		}
		return checkDelete(entity, entities);
	}
	
	protected List<String> distinctNameAsList(String propertyName) {
		List<String> result = new ArrayList<String>();
		for (Entity e : this.getAll().asIterable()) {
			if (!result.contains(e.getProperty(propertyName).toString())) {
				result.add(e.getProperty(propertyName).toString());
			}
		}
		return result;
	}
	
	protected String getKindName() {
		return this.getClass().getSimpleName();
	}
	
	protected static Boolean hasEntity(Iterable<Entity> entities) {
		try {
			for (Entity e : entities) {
				if (e != null) {
					return true;
				}
			}
		} catch (Exception e) {
			//
		}
		return false;
	}
	
	protected List<String> nameAsList(String propertyName) {
		List<String> result = new ArrayList<String>();
		for (Entity e : this.getAll().asIterable()) {
			result.add(e.getProperty(propertyName).toString());
		}
		return result;
	}
	
	public PreparedQuery get(Filter filter) {
		return Datastore.get(getKindName(), filter);
	}
	
	public Entity get(long key) {
		return Datastore.get(getKindName(), key);
	}
	
	public PreparedQuery get(String propertyName, Object value) {
		return Datastore.get(getKindName(), propertyName, value);
	}
	
	public PreparedQuery getAll() {
		return Datastore.get(getKindName(), null, null);
	}
	
}
